import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class SocketServer implements Runnable{
    Socket socket;
    Thread thread;
    public SocketServer (Socket socket){
        this.socket=socket;
        start();
    }
    public void run() {
        while (true){
            try {
                DataInputStream input = new DataInputStream(socket.getInputStream());
                Send(input.readUTF());
            } catch (IOException e) {
                try {
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                clear();
                break;
            }
        }
    }
    public void start(){
        thread = new Thread(this);
        thread.start();
    }
    void Send(String str) throws IOException {
        for (SocketServer server : SocketServerMain.list){
            DataOutputStream out = new DataOutputStream(server.socket.getOutputStream());
            out.writeUTF(str);
        }
    }
    void clear(){
        for (int i =SocketServerMain.list.size()-1;i>=0;i--){
            try {
                SocketServerMain.list.get(i).socket.getInputStream();
            } catch (IOException e) {
                SocketServerMain.list.remove(i);
            }
        }
    }
}